package gui;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.SystemColor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyVetoException;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;

import com.jgoodies.forms.factories.FormFactory;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.RowSpec;
import com.michaelbaranov.microba.calendar.DatePicker;

import data.DepartmentData;
import data.Order;
import data.Order.OrderState;
import data.OrderDepartment;

public class OrderInfoTabPanel extends JPanel {
	private static final long serialVersionUID = 1998545215309951073L;

	private int mOrderDbId = 0;
	private JTextField mOrderNumber;
	private JTextField mCostUnit;
	private DatePicker mDatePicker;
	private JComboBox<String> mPaymentMethodCombo;
	private OrderState mOrderState = OrderState.New;
	private JLabel mOrderStateLabel;
	private JPanel mObjectsPanel;

	private OrderTabbedPane mParent = null;

	public OrderInfoTabPanel(OrderTabbedPane parent) {
		mParent = parent;
		
		setLayout(new BorderLayout(0, 0));

		JPanel panel_7 = new JPanel();
		panel_7.setBackground(SystemColor.window);
		panel_7.setBorder(new TitledBorder(null, "Og\u00F3lne",
				TitledBorder.LEADING, TitledBorder.TOP, null, null));
		add(panel_7, BorderLayout.NORTH);
		panel_7.setLayout(new FormLayout(new ColumnSpec[] {
				FormFactory.RELATED_GAP_COLSPEC,
				ColumnSpec.decode("left:default"),
				FormFactory.RELATED_GAP_COLSPEC,
				ColumnSpec.decode("default:grow"), }, new RowSpec[] {
				FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC,
				FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC,
				FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC,
				FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC,
				FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC,
				FormFactory.RELATED_GAP_ROWSPEC, }));

		JLabel lblNewLabel = new JLabel("Numer zam\u00F3wienia:");
		panel_7.add(lblNewLabel, "2, 2, left, default");

		mOrderNumber = new JTextField();
		panel_7.add(mOrderNumber, "4, 2, fill, default");
		mOrderNumber.setColumns(10);

		JLabel lblNewLabel_1 = new JLabel("Jednostka kosztowa:");
		panel_7.add(lblNewLabel_1, "2, 4, left, default");

		mCostUnit = new JTextField();
		panel_7.add(mCostUnit, "4, 4, fill, default");
		mCostUnit.setColumns(10);

		JLabel lblData = new JLabel("Data:");
		panel_7.add(lblData, "2, 6, left, default");

		mDatePicker = new DatePicker();
		mDatePicker.setShowNoneButton(false);
		mDatePicker.setFieldEditable(false);
		// mDatePicker.addActionListener(new ActionListener() {
		//
		// @Override
		// public void actionPerformed(ActionEvent arg0) {
		// Calendar c = new GregorianCalendar();
		// c.set(Calendar.HOUR_OF_DAY, 0);
		// c.set(Calendar.MINUTE, 0);
		// c.set(Calendar.SECOND, 0);
		// if (mDatePicker.getDate().before(c.getTime())) {
		// JOptionPane.showMessageDialog(MainPanel.this,
		// "Nie mo�esz wybra� daty z przesz�o�ci.", "B��d",
		// JOptionPane.ERROR_MESSAGE);
		// try {
		// mDatePicker.setDate(new Date());
		// } catch (PropertyVetoException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		// }
		// }
		// });
		panel_7.add(mDatePicker, "4, 6, fill, default");

		JLabel lblPatno = new JLabel("P\u0142atno\u015B\u0107:");
		panel_7.add(lblPatno, "2, 8, left, default");

		mPaymentMethodCombo = new JComboBox<>();
		mPaymentMethodCombo.addItem("Got\u00F3wka");
		mPaymentMethodCombo.addItem("Przelew");
		panel_7.add(mPaymentMethodCombo, "4, 8, fill, default");

		JLabel lblNewLabel_2 = new JLabel("Stan zam\u00F3wienia:");
		panel_7.add(lblNewLabel_2, "2, 10");

		mOrderStateLabel = new JLabel("Nowe");
		panel_7.add(mOrderStateLabel, "4, 10");

		mObjectsPanel = new JPanel();
		mObjectsPanel.setBackground(SystemColor.window);
		mObjectsPanel.setBorder(new TitledBorder(null,
				"Wyb\u00F3r obiekt\u00F3w", TitledBorder.LEADING,
				TitledBorder.TOP, null, null));
		mObjectsPanel.setLayout(new BoxLayout(mObjectsPanel, BoxLayout.Y_AXIS));

		JScrollPane scrollPane = new JScrollPane(mObjectsPanel);
		scrollPane.setBorder(BorderFactory.createEmptyBorder());

		scrollPane.setPreferredSize(mObjectsPanel.getSize());
		add(scrollPane, BorderLayout.CENTER);
	}

	public void setObjects(Collection<DepartmentData> depDatas) {
		for (final DepartmentData objectData : depDatas) {
			MyCheckBox chkBox = new MyCheckBox(objectData);
			chkBox.setBackground(SystemColor.window);
			chkBox.addActionListener(new ActionListener() {

				@Override
				public void actionPerformed(ActionEvent arg0) {
					MyCheckBox source = (MyCheckBox) arg0.getSource();
					if (source.isSelected()) {
						mParent.addTab(source.getDepartment().getNameShort(),
								null, new ObjectOrderPanel(
										OrderInfoTabPanel.this, objectData),
								null);
					} else {
						for (Component component : mParent.getComponents()) {
							if (component instanceof ObjectOrderPanel
									&& ((ObjectOrderPanel) component)
											.getDepartmentData()
											.getNameShort()
											.equals(source.getDepartment()
													.getNameShort())) {
								mParent.remove(component);
								break;
							}
						}
					}
				}
			});
			mObjectsPanel.add(chkBox);
		}
		mObjectsPanel.revalidate();
		mObjectsPanel.repaint();
	}

	public void resetOrder() {
		mOrderDbId = 0;
		mOrderState = OrderState.New;
		mOrderNumber.setText("");
		mCostUnit.setText("");
		try {
			mDatePicker.setDate(new Date());
		} catch (PropertyVetoException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		mPaymentMethodCombo.setSelectedIndex(0);
		mOrderStateLabel.setText("Nowe");
		unselectObjects();
	}
	
	private void unselectObjects() {
		for (Component component : mObjectsPanel.getComponents())
			if (component instanceof MyCheckBox)
				((MyCheckBox) component).setSelected(false);
	}

	public void loadOrder(Order order) {
		mOrderDbId = order.getDbId();
		mOrderNumber.setText(order.getNumber());
		mCostUnit.setText(order.getCostUnit());
		mPaymentMethodCombo.setSelectedIndex(order.getPaymentMethod());
		mOrderStateLabel.setText(order.getState().toString());
		loadObjects(order.getOrderDepartments());
		mOrderState = order.getState();
		mParent.enableEdit(mOrderState != OrderState.Accepted
				&& mOrderState != OrderState.Submitted);
	}
	
	private void loadObjects(HashMap<DepartmentData, OrderDepartment> departments) {
		for (DepartmentData dd : departments.keySet()) {
			for (Component component : mObjectsPanel.getComponents()) {
				if (component instanceof MyCheckBox
						&& ((MyCheckBox) component).getDepartment().equals(dd)) {
					((MyCheckBox) component).setSelected(true);
					mParent.addTab(dd.getNameShort(), null,
							new ObjectOrderPanel(OrderInfoTabPanel.this, dd,
									departments.get(dd)), null);
					break;
				}
			}
		}
	}

	public boolean isOrderEditable() {
		return mOrderState != OrderState.Submitted
				&& mOrderState != OrderState.Accepted;
	}

	public void changeOrderState(OrderState state) {
		mOrderState = state;
		mOrderStateLabel.setText(state.toString());
	}

	public void setOrderDbId(int orderDbId) {
		mOrderDbId = orderDbId;
	}

	// public int getOrderDbId() {
	// return mOrderDbId;
	// }
	//
	// public String getOrderName() {
	// return mOrderNumber.getText();
	// }
	//
	// public String getCostInfo() {
	// return mCostUnit.getText();
	// }
	//
	// public Date getDate() {
	// return mDatePicker.getDate();
	// }
	//
	// public int getPaymentMethod() {
	// return mPaymentMethodCombo.getSelectedIndex();
	// }
	//
	// public OrderState getOrderState() {
	// return mOrderState;
	// }

	public void enableEdit(boolean enable) {
		mOrderNumber.setEnabled(enable);
		mCostUnit.setEnabled(enable);
		mDatePicker.setEnabled(enable);
		mPaymentMethodCombo.setEnabled(enable);
		for (Component component : mObjectsPanel.getComponents())
			component.setEnabled(enable);
	}

	public Order createOrder(HashMap<DepartmentData, OrderDepartment> hashMap) {
		if (mOrderState == OrderState.New)
			mOrderState = OrderState.Draft;
		return new Order(mOrderDbId, mOrderNumber.getText(),
				mCostUnit.getText(), mDatePicker.getDate(),
				mPaymentMethodCombo.getSelectedIndex(), mOrderState, hashMap);
	}

	public void refreshObjects(Order order) {
		unselectObjects();
		mObjectsPanel.removeAll();
		setObjects(order.getOrderDepartments().keySet());
		loadObjects(order.getOrderDepartments());
		mParent.enableEdit(isOrderEditable());
	}
}
